const express = require('express');
const cors = require('cors');
const { Sequelize, DataTypes } = require('sequelize');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http, { cors: { origin: '*' } });

// 配置Node.js接收大型请求
http.maxHeaderSize = 80000; // 增加HTTP头大小

// 中间件配置
app.use(express.static('public'));
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// SQLite数据库连接
const sequelize = new Sequelize({ dialect: 'sqlite', storage: 'database.sqlite' });

// 数据模型定义
const Conversation = sequelize.define('Conversation', {
  name: { type: DataTypes.STRING, allowNull: false }
});

const Message = sequelize.define('Message', {
  content: { type: DataTypes.TEXT, allowNull: false },
  type: { type: DataTypes.ENUM('text', 'image'), defaultValue: 'text' },
  sender: { type: DataTypes.ENUM('user', 'bot'), allowNull: false },
  timestamp: { type: DataTypes.DATE, defaultValue: DataTypes.NOW }
});

// 建立关联关系
Conversation.hasMany(Message, { foreignKey: 'conversation_id' });
Message.belongsTo(Conversation, { foreignKey: 'conversation_id' });

// API路由
// 获取所有会话
app.get('/api/conversations', async (req, res) => {
  const conversations = await Conversation.findAll({ order: [['createdAt', 'DESC']] });
  res.json(conversations);
});

// 取消注释并修复会话创建端点
app.post('/api/conversations', async (req, res) => {
  const { name } = req.body;
  try {
    const conversation = await Conversation.create({ name });
    io.emit('conversation_update');
    res.json(conversation);
  } catch (error) {
    console.error('Error creating conversation:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 添加消息创建端点
app.post('/api/messages', async (req, res) => {
  const { conversation_id, sender, type, content } = req.body;
  try {
    const message = await Message.create({
      conversation_id,
      sender,
      type,
      content,
      timestamp: new Date()
    });
    io.emit('message_update', { conversation_id });
    res.json(message);
  } catch (error) {
    console.error('Error creating message:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 更新会话名称
app.put('/api/conversations/:id', async (req, res) => {
  const { name } = req.body;
  await Conversation.update({ name }, { where: { id: req.params.id } });
  io.emit('conversation_update');
  res.sendStatus(200);
});

// 删除会话
app.delete('/api/conversations/:id', async (req, res) => {
  await Conversation.destroy({ where: { id: req.params.id } });
  io.emit('conversation_update');
  res.sendStatus(200);
});

// 获取会话消息
app.get('/api/messages', async (req, res) => {
  const { conversation_id } = req.query;
  const messages = await Message.findAll({
    where: { conversation_id },
    order: [['timestamp', 'ASC']]
  });
  res.json(messages);
});

// 兜底路由
app.get('*', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

// WebSocket连接
io.on('connection', (socket) => {
  console.log('客户端连接');
});

// // 数据库初始化
// async function init() {
//   // 仅同步结构，不删除现有数据
//   await sequelize.sync(); // 不使用 force: true

//   // 创建测试会话和消息
//   const conv1 = await Conversation.create({ name: '技术支持会话' });
//   await Message.bulkCreate([
//     { conversation_id: conv1.id, content: '我的账号无法登录', sender: 'user' },
//     { conversation_id: conv1.id, content: '请检查网络连接', sender: 'bot' }
//   ]);

//   const conv2 = await Conversation.create({ name: '产品咨询' });
//   await Message.bulkCreate([
//     { conversation_id: conv2.id, content: '这款产品有现货吗？', sender: 'user' },
//     { conversation_id: conv2.id, content: '目前库存充足', sender: 'bot' }
//   ]);

//   console.log('数据库初始化完成！');
// }

// 启动服务
sequelize.sync().then(() => {
  http.listen(3000, () => {
    console.log('服务运行在 http://localhost:3000');
  });
});
